package websocket

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// Service 定义服务生命周期接口
 type Service interface {
	Start() error
	Stop() error
}

// WebSocketServer 实现Service接口
func (s *WebSocketServer) Start() error {
	// 启动WebSocket服务器
	go func() {
		log.Printf("WebSocket server started on %s\n", "0.0.0.0:9988")
		server := &http.Server{Addr: "0.0.0.0:9988", Handler: s}
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("Listen: %s\n", err)
		}
	}()
	return nil
}

// Stop 优雅关闭WebSocket服务器
func (s *WebSocketServer) Stop() error {
	log.Println("Shutting down WebSocket server...")

	// 创建一个5秒的超时上下文
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 关闭所有房间
	// s.roomManager.CloseAllRooms()
	log.Println("All rooms closed")

	// 关闭HTTP服务器
	server := &http.Server{Addr: "0.0.0.0:9988"}
	if err := server.Shutdown(ctx); err != nil {
		log.Fatalf("Server forced to shutdown: %s\n", err)
		return err
	}

	log.Println("WebSocket server exiting")
	return nil
}

// SetupSignalHandler 设置信号处理器，用于优雅关闭服务
func SetupSignalHandler(svc Service) {
	// 创建一个信号通道
	quit := make(chan os.Signal, 1)
	// 监听SIGINT和SIGTERM信号
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	// 阻塞直到接收到信号
	<-quit
	log.Println("Received quit signal, shutting down...")

	// 调用服务的Stop方法
	if err := svc.Stop(); err != nil {
		log.Fatalf("Failed to stop service: %v\n", err)
	}
}